import { getUserPermissionListApi, setRolePermissionApi } from '@/services/api';
import {
  DrawerForm,
  ProFormInstance,
  ProFormItem,
} from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Form, Skeleton, Tree } from 'antd';
import { isEmpty, isEqual } from 'lodash';
import React, { useRef } from 'react';
interface Props {
  open?: boolean;
  info?: any;
  close?: () => void;
  onFinish?: () => void;
  type?: string;
}

const CreatePermission: React.FC<Props> = ({
  open,
  close,
  info,
  onFinish,
  type,
}) => {
  const [form] = Form.useForm();

  const formRef = useRef<ProFormInstance>();

  const [keys, setKeys] = React.useState([]);
  const [halfCheckedKeys, sethalfCheckedKeys] = React.useState<any>([]);

  // 获取权限树
  const { data: permissionList, loading } = useRequest(
    async () => {
      const _res = await getUserPermissionListApi({});

      return _res?.data;
    },
    {
      onSuccess: (data) => {
        console.log('data', data);
        // 所有第一级id
        const _fitst_ids = data?.map((item: any) => item.id);

        // 所有最后一级id （只要没有children就是最后一集）
        const last_ids: any = [];

        const _second_ids = [];

        data?.forEach((item: any) => {
          if (!isEmpty(item.children)) {
            item.children.forEach((child: any) => {
              if (!isEmpty(child.children)) {
                child.children.forEach((_haha) => {
                  last_ids.push(_haha.id);
                });
              } else {
                last_ids.push(child.id);
              }
            });
          }
        });

        console.log('last_idslast_idslast_idslast_ids', last_ids);

        const fuhe_id = info?.permissions?.filter(
          (item: any) => !last_ids.includes(item),
        );
        console.log('_fitst_ids', {
          last_ids,
          'info?.permissions': info?.permissions,
          fuhe_id,
        });

        setKeys(info?.permissions?.filter((e) => last_ids.includes(e)));
        sethalfCheckedKeys(fuhe_id);
      },
    },
  );
  return (
    <DrawerForm
      formRef={formRef}
      title={info.id ? '编辑角色权限配置' : '新建角色权限配置'}
      form={form}
      open={open}
      width={'38%'}
      onOpenChange={(visible) => {
        if (!visible) {
          close?.();
        }
      }}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
      }}
      initialValues={{ ...info }}
      onFinish={async (values) => {
        console.log('values', values);
        // return;

        try {
          const { msg } = await setRolePermissionApi(info.id, {
            ids: [...keys, ...halfCheckedKeys],
            // parent: info.id ? info.id : undefined,
            // parent_id: ''
          });
          onFinish?.();
          // 不返回不会关闭弹框
          return true;
        } catch (error) {}
      }}
    >
      <Skeleton loading={loading}>
        <ProFormItem name="ids" label="权限">
          <Tree
            checkedKeys={{
              checked: keys,
              halfChecked: halfCheckedKeys,
            }}
            checkable
            treeData={permissionList}
            fieldNames={{
              title: 'label',
              key: 'id',
              children: 'children',
            }}
            onSelect={(val) => {
              console.log('val', val);
            }}
            onCheck={(val, info) => {
              console.log('infoinfoinfo', { val, info });
              sethalfCheckedKeys(info.halfCheckedKeys);
              setKeys(val);
            }}
          />
        </ProFormItem>
      </Skeleton>
    </DrawerForm>
  );
};

export default React.memo(CreatePermission, (prev, next) =>
  isEqual(prev, next),
);
